﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RuoVea.ExDto;
using RuoVea.ExEnum;
using RuoVea.ExSugar;
using RuoVea.ExUtil;
using RuoVea.H5DS.Dto;
using RuoVea.ExDto.Language;
using RuoVea.H5DS.Models;

namespace RuoVea.H5DS.Controllers;

[Authorize(Roles = "None")]
public partial class H5PageDataController : Controller
{
    /// <summary>
    /// 
    /// </summary>
    private readonly SugarRepository<H5PageData> _thisRepository;
    private readonly ICurrentUser _currentUser;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="thisRepository"></param>
    /// <param name="currentUser"></param>
    public H5PageDataController(SugarRepository<H5PageData> thisRepository, ICurrentUser currentUser)
    {
        _thisRepository = thisRepository;
        _currentUser = currentUser;
    }

    public IActionResult Index(string appId)
    {
        ViewBag.appId = appId;
        return View();
    }


    /// <summary>
    /// 查询所有/分页
    /// </summary>
    /// <returns></returns>
    [HttpPost("H5PageData/pages")]
    public async Task<RestfulResult<PageResult<H5PageData>>> GetPagesAsync()
    {
        var restful = new RestfulResult<PageResult<H5PageData>>() { Code = CodeStatus.OK };
        using var sr = new StreamReader(Request.Body);
        string dataStr = await sr.ReadToEndAsync();
        if (Request.Body.CanSeek)
            Request.Body.Position = 0;
        if (string.IsNullOrWhiteSpace(dataStr))
            throw new Exception("未提供上传数据。请在Request.Body中携带上传数据。");
        H5PageDataPageParam? data = JsonConvert.DeserializeObject<H5PageDataPageParam>(dataStr);
        data ??= new H5PageDataPageParam { PageNo = 1, PageSize = 10 };

        var query = await _thisRepository.AsQueryable()
            //.Where(u => u.Creator == _currentUser.UserId)
            .Where(u => u.TempId == data.appId)
            .ToPageAsync(data.PageNo, data.PageSize);

        restful.Data = query;
        return restful;
    }

    /// <summary>
    /// 查询所有/分页
    /// </summary>
    /// <returns></returns>
    [HttpPost("H5PageData/list")]
    public async Task<RestfulResult<PageResult<H5PageData>>> GetlistAsync()
    {
        var restful = new RestfulResult<PageResult<H5PageData>>() { Code = CodeStatus.OK };
        PageParam data = new PageParam { PageNo = 1, PageSize = 100 };
        var query = await _thisRepository.AsQueryable()
             .Where(u => u.IsDisable == YesOrNot.N)
             .Where(u => u.Creator == _currentUser.UserId)

             .Select(u => new H5PageData
             {
                 Id = u.Id,
                 Name = u.Name,

                 IsDelete = u.IsDelete,
                 IsDisable = u.IsDisable,
                 Sort = u.Sort,
                 Remark = u.Remark,
                 Creator = u.Creator,
                 CreateTime = u.CreateTime,
                 Value1 = u.Value1,
                 Value2 = u.Value2,
                 Value3 = u.Value3,
                 Value4 = u.Value4,
                 Value5 = u.Value5,
             })
            .ToPageAsync(data.PageNo, data.PageSize);
        restful.Data = query;
        return restful;
    }
    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [HttpPost("H5PageData/submit")]
    public async Task<RestfulResult> SubmitAsync([FromBody] H5PageData data)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };
        if (data.Id == 0)
        {
            var isExist = await _thisRepository.IsAnyAsync(u => (u.Name == data.Name)/* && u.Creator == _currentUser.UserId*/);
            if (isExist)
            {
                restful.Message = ErrorEnum.D3001.GetDescription(i18n.ResourceManager);
                return restful;
            }
            bool result = await _thisRepository.InsertAsync(data);
            if (result)
            {
                restful.Data = result;
                restful.Code = CodeStatus.OK;
                return restful;
            }
            else
            {
                restful.Message = "添加失败";
                return restful;
            }
        }
        else
        {
            var isExist = await _thisRepository.IsAnyAsync(u => u.Id == data.Id /*&& u.Creator == _currentUser.UserId*/);
            if (!isExist)
            {
                restful.Message = ErrorEnum.D3000.GetDescription(i18n.ResourceManager);
                return restful;
            }
            bool result = await _thisRepository.UpdateAsync(data);
            if (result)
            {
                restful.Data = result;
                restful.Code = CodeStatus.OK;
                return restful;
            }
            else
            {
                restful.Message = "修改失败";
                return restful;
            }
        }
    }

    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpDelete("H5PageData/delete/{id:long}")]
    public async Task<RestfulResult> DeleteAsync(long id)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };

        if (id == 0)
        {
            restful.Message = "删除失败";
            return restful;
        }
        bool isDelete = await _thisRepository.DeleteByIdAsync(id);
        if (isDelete)
        {
            restful.Data = isDelete;
            restful.Message = "删除成功";
            restful.Code = CodeStatus.OK;
            return restful;
        }
        else
        {
            restful.Data = isDelete;
            restful.Message = "删除失败";
            return restful;
        }
    }
}
